import axios, { CancelToken } from 'axios'; // 引入axios
import { getToken } from '@/utils/auth';
import store from '@/store';
// import router from '@/router';
import { ElMessageBox, ElMessage } from 'element-plus';

const sendError = (error = {}) => {
  const { config = {}, response, request } = error;

  let { message = 'Error' } = error;

  if (config.customErrorElMessage) {
    console.warn('API请求异常，调用方自行处理错误消息：' + message, config, message)
    return
  }
  // 字符串
  if (typeof error === 'string') {
    message = error; // 框架抛出纯字符串异常
  }

  let isLogin = false;
  if (response && response.data) {
    const data = response.data;

    // 登录页错误消息,改成醒目一点提示框  update by shengl 20200819
    if (data.error_description) {
      isLogin = true;
    }

    message = data.error_description || // 登录页的错误消息
      data.ERROR_MSG || data.errorMsg ||// 常规业务错误消息
      data.Message ||// 后台异常错误消息
      message
  }

  // 登录页错误消息,改成醒目一点提示框  update by shengl 20200819
  if (isLogin) {
    ElMessageBox.alert('', message, {
      confirmButtonText: '确定',
      type: 'warning',
      center: true
    })
  } else {
    ElMessage({
      message: message || 'Error',
      type: 'error',
      duration: 3 * 1000
    })
  }
  console.error('API请求异常：' + message, error, config, request, response)
}

const pending = {};
// 同一请求不能连续发两次
const removePending = (key, isRequest = false) => {
  if (pending[key] && isRequest) {
    pending[key]("取消重复请求!");
  }
  if (pending[key]) {
    delete pending[key];
  }
}

// 通用请求拦截器
export const baseRequestInterceptor = (axiosInstance) => {
  axiosInstance.interceptors.request.use(
    (config) => {
      const key = config.url + '&' + config.method;
      removePending(key, true);
      config.cancelToken = new CancelToken((cancel) => {
        pending[key] = cancel;
      })
      return config;
    },
    (error) => {
      return Promise.reject(error)
    }
  )
}

let reLoginConfirmFlag = false;
// 通用响应拦截器
export const commonResponseInterceptor = (axiosInstance) => {
  axiosInstance.interceptors.response.use(
    response => {
      const key = response.config.url + '&' + response.config.method;
      removePending(key);
      return response
    },
    error => {
      console.log(error);
      // 出现error则需要重新登陆 to re-login
      localStorage.clear();
      sessionStorage.clear();
      if (!reLoginConfirmFlag) {
        reLoginConfirmFlag = true;
        ElMessageBox.confirm('您已注销，您可以取消以停留在此页，或重新登录', '确认退出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/logout').then(() => {
            console.log('reload');
            location.reload();
          })
        }).finally(() => (reLoginConfirmFlag = false))
      
      }
      sendError(error)
      return Promise.reject(error)
    }
  )
}

const rpmService = axios.create({
  baseURL: import.meta.env.VITE_RPM_API,
  timeout: 30000
})

const pdmService = axios.create({
  baseURL: import.meta.env.VITE_PDM_API,
  timeout: 30000
})

// 实例的拦截器
const serverList = [pdmService, rpmService];

serverList.forEach(service => {
  // 通用拦截器
  baseRequestInterceptor(service);
  commonResponseInterceptor(service);
})

// 单独的拦截器
pdmService.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['Authorization'] = `Bearer ${getToken()}`;
    }
    return config;
  }
)

rpmService.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers.token = getToken();
    }
    return config
  },
  data => {
    return data
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

pdmService.interceptors.response.use(
  response => {
    const { result, errors } = response.data;
    if (result != "ERROR") {
      return response.data
    }
    ElMessage({
      message: errors.message || 'Error',
      type: 'error',
      duration: 5 * 1000
    });
    const code = errors.code;
    // 当获取不到用户的 userID 时,将重新跳转到首页
    if(code == -2) {
      sessionStorage.clear();
      window.location.href = '#/login';
    }
    return Promise.reject(new Error(errors.message || 'Error'))
  }
)

// response interceptor
rpmService.interceptors.response.use(
  response => {
    const res = response.data;
    const code = res.code;
    if ( code == '200' || code == '505' || code == '510') {
      //返回结果
      return res
    }
    ElMessage({
      message: res.message || 'Error',
      type: 'error',
      duration: 5 * 1000
    });

    return Promise.reject(new Error(res.message || 'Error'))
  }
)

export { rpmService, pdmService };